<template>
  <div class="aftersales-statistics-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>售后统计分析</h3>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
            />
            <el-button type="primary" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出报表
            </el-button>
          </div>
        </div>
      </template>

      <!-- 核心指标卡片 -->
      <div class="kpi-cards">
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="kpi-card">
              <div class="kpi-icon" style="background: #ecf5ff; color: #409eff;">
                <el-icon><Document /></el-icon>
              </div>
              <div class="kpi-content">
                <div class="kpi-label">总售后单数</div>
                <div class="kpi-value">{{ kpi.totalCount }}</div>
                <div class="kpi-trend">
                  <span :class="kpi.countTrend > 0 ? 'trend-up' : 'trend-down'">
                    {{ kpi.countTrend > 0 ? '↑' : '↓' }} {{ Math.abs(kpi.countTrend) }}%
                  </span>
                  较上期
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="kpi-card">
              <div class="kpi-icon" style="background: #fef0f0; color: #f56c6c;">
                <el-icon><Money /></el-icon>
              </div>
              <div class="kpi-content">
                <div class="kpi-label">退款总金额</div>
                <div class="kpi-value">¥{{ kpi.totalRefund.toLocaleString() }}</div>
                <div class="kpi-trend">
                  <span :class="kpi.refundTrend > 0 ? 'trend-up' : 'trend-down'">
                    {{ kpi.refundTrend > 0 ? '↑' : '↓' }} {{ Math.abs(kpi.refundTrend) }}%
                  </span>
                  较上期
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="kpi-card">
              <div class="kpi-icon" style="background: #f0f9ff; color: #67c23a;">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="kpi-content">
                <div class="kpi-label">完成率</div>
                <div class="kpi-value">{{ kpi.completionRate }}%</div>
                <div class="kpi-trend">
                  <span :class="kpi.completionTrend > 0 ? 'trend-up' : 'trend-down'">
                    {{ kpi.completionTrend > 0 ? '↑' : '↓' }} {{ Math.abs(kpi.completionTrend) }}%
                  </span>
                  较上期
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="kpi-card">
              <div class="kpi-icon" style="background: #fdf6ec; color: #e6a23c;">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="kpi-content">
                <div class="kpi-label">平均处理时长</div>
                <div class="kpi-value">{{ kpi.avgHandleTime }}h</div>
                <div class="kpi-trend">
                  <span :class="kpi.timeTrend < 0 ? 'trend-up' : 'trend-down'">
                    {{ kpi.timeTrend < 0 ? '↓' : '↑' }} {{ Math.abs(kpi.timeTrend) }}%
                  </span>
                  较上期
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <el-row :gutter="16" style="margin-top: 20px;">
        <!-- 售后趋势图 -->
        <el-col :span="12">
          <el-card shadow="never">
            <template #header>
              <div class="card-header">
                <span>售后趋势分析</span>
                <el-radio-group v-model="trendType" size="small" @change="loadTrendData">
                  <el-radio-button label="day">日</el-radio-button>
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="trendChart" style="height: 300px;"></div>
          </el-card>
        </el-col>

        <!-- 售后类型分布 -->
        <el-col :span="12">
          <el-card shadow="never">
            <template #header>
              <span>售后类型分布</span>
            </template>
            <div ref="typeChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="16" style="margin-top: 16px;">
        <!-- 售后原因分析 -->
        <el-col :span="12">
          <el-card shadow="never">
            <template #header>
              <span>售后原因分析</span>
            </template>
            <div ref="reasonChart" style="height: 300px;"></div>
          </el-card>
        </el-col>

        <!-- 商品售后排行 -->
        <el-col :span="12">
          <el-card shadow="never">
            <template #header>
              <span>商品售后排行 TOP10</span>
            </template>
            <div ref="productChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 售后明细表 -->
      <el-card shadow="never" style="margin-top: 16px;">
        <template #header>
          <span>售后明细数据</span>
        </template>
        
        <el-table :data="detailData" stripe>
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="totalCount" label="售后单数" width="100" />
          <el-table-column prop="returnCount" label="退货退款" width="100" />
          <el-table-column prop="refundOnlyCount" label="仅退款" width="100" />
          <el-table-column prop="exchangeCount" label="换货" width="100" />
          <el-table-column prop="repairCount" label="维修" width="100" />
          <el-table-column prop="totalAmount" label="退款金额" width="120">
            <template #default="{ row }">
              ¥{{ row.totalAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="completedCount" label="已完成" width="100" />
          <el-table-column prop="completionRate" label="完成率" width="100">
            <template #default="{ row }">
              {{ row.completionRate }}%
            </template>
          </el-table-column>
          <el-table-column prop="avgHandleTime" label="平均处理时长" width="120">
            <template #default="{ row }">
              {{ row.avgHandleTime }}小时
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Money, CircleCheck, Clock, Download } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 日期范围
const dateRange = ref([])

// KPI数据
const kpi = reactive({
  totalCount: 1256,
  countTrend: 8.5,
  totalRefund: 456780.50,
  refundTrend: -3.2,
  completionRate: 92.5,
  completionTrend: 5.6,
  avgHandleTime: 18.5,
  timeTrend: -12.3
})

// 趋势类型
const trendType = ref('day')

// 图表实例
const trendChart = ref(null)
const typeChart = ref(null)
const reasonChart = ref(null)
const productChart = ref(null)

let trendChartInstance = null
let typeChartInstance = null
let reasonChartInstance = null
let productChartInstance = null

// 明细数据
const detailData = ref([
  {
    date: '2025-01-19',
    totalCount: 45,
    returnCount: 18,
    refundOnlyCount: 12,
    exchangeCount: 10,
    repairCount: 5,
    totalAmount: 28560.00,
    completedCount: 42,
    completionRate: 93.3,
    avgHandleTime: 16.5
  },
  {
    date: '2025-01-18',
    totalCount: 52,
    returnCount: 22,
    refundOnlyCount: 15,
    exchangeCount: 10,
    repairCount: 5,
    totalAmount: 35280.00,
    completedCount: 48,
    completionRate: 92.3,
    avgHandleTime: 17.2
  },
  {
    date: '2025-01-17',
    totalCount: 38,
    returnCount: 15,
    refundOnlyCount: 11,
    exchangeCount: 8,
    repairCount: 4,
    totalAmount: 22450.00,
    completedCount: 35,
    completionRate: 92.1,
    avgHandleTime: 18.5
  },
  {
    date: '2025-01-16',
    totalCount: 41,
    returnCount: 17,
    refundOnlyCount: 13,
    exchangeCount: 7,
    repairCount: 4,
    totalAmount: 26890.00,
    completedCount: 38,
    completionRate: 92.7,
    avgHandleTime: 19.0
  },
  {
    date: '2025-01-15',
    totalCount: 48,
    returnCount: 20,
    refundOnlyCount: 14,
    exchangeCount: 9,
    repairCount: 5,
    totalAmount: 31200.00,
    completedCount: 44,
    completionRate: 91.7,
    avgHandleTime: 20.5
  }
])

// 初始化趋势图表
const initTrendChart = () => {
  if (trendChartInstance) {
    trendChartInstance.dispose()
  }
  
  trendChartInstance = echarts.init(trendChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['售后单数', '退款金额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['01-15', '01-16', '01-17', '01-18', '01-19']
    },
    yAxis: [
      {
        type: 'value',
        name: '单数',
        position: 'left'
      },
      {
        type: 'value',
        name: '金额(万元)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '售后单数',
        type: 'line',
        data: [48, 41, 38, 52, 45],
        smooth: true,
        itemStyle: {
          color: '#409eff'
        }
      },
      {
        name: '退款金额',
        type: 'line',
        yAxisIndex: 1,
        data: [3.12, 2.69, 2.25, 3.53, 2.86],
        smooth: true,
        itemStyle: {
          color: '#f56c6c'
        }
      }
    ]
  }
  
  trendChartInstance.setOption(option)
}

// 初始化类型分布图表
const initTypeChart = () => {
  if (typeChartInstance) {
    typeChartInstance.dispose()
  }
  
  typeChartInstance = echarts.init(typeChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        name: '售后类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        data: [
          { value: 456, name: '退货退款', itemStyle: { color: '#f56c6c' } },
          { value: 312, name: '仅退款', itemStyle: { color: '#e6a23c' } },
          { value: 285, name: '换货', itemStyle: { color: '#409eff' } },
          { value: 203, name: '维修', itemStyle: { color: '#67c23a' } }
        ]
      }
    ]
  }
  
  typeChartInstance.setOption(option)
}

// 初始化原因分析图表
const initReasonChart = () => {
  if (reasonChartInstance) {
    reasonChartInstance.dispose()
  }
  
  reasonChartInstance = echarts.init(reasonChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: ['其他', '收到假货', '商品与描述不符', '不想要了', '发错货', '商品破损', '质量问题']
    },
    series: [
      {
        name: '次数',
        type: 'bar',
        data: [45, 78, 125, 156, 189, 234, 389],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#409eff' },
            { offset: 1, color: '#667eea' }
          ])
        }
      }
    ]
  }
  
  reasonChartInstance.setOption(option)
}

// 初始化商品排行图表
const initProductChart = () => {
  if (productChartInstance) {
    productChartInstance.dispose()
  }
  
  productChartInstance = echarts.init(productChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: [
        '商品J',
        '商品I',
        '商品H',
        '商品G',
        '商品F',
        '商品E',
        '商品D',
        '商品C',
        '商品B',
        '商品A'
      ]
    },
    series: [
      {
        name: '售后次数',
        type: 'bar',
        data: [12, 15, 18, 21, 24, 28, 32, 35, 40, 45],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#f56c6c' },
            { offset: 1, color: '#e6a23c' }
          ])
        }
      }
    ]
  }
  
  productChartInstance.setOption(option)
}

// 日期改变
const handleDateChange = () => {
  loadData()
}

// 导出报表
const handleExport = () => {
  ElMessage.success('报表导出成功')
}

// 加载趋势数据
const loadTrendData = () => {
  initTrendChart()
}

// 加载数据
const loadData = () => {
  nextTick(() => {
    initTrendChart()
    initTypeChart()
    initReasonChart()
    initProductChart()
  })
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  trendChartInstance?.resize()
  typeChartInstance?.resize()
  reasonChartInstance?.resize()
  productChartInstance?.resize()
}

onMounted(() => {
  loadData()
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.aftersales-statistics-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.kpi-cards {
  margin-bottom: 20px;
}

.kpi-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
}

.kpi-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.kpi-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  margin-right: 15px;
}

.kpi-content {
  flex: 1;
}

.kpi-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.kpi-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.kpi-trend {
  font-size: 12px;
  color: #909399;
}

.trend-up {
  color: #67c23a;
  font-weight: bold;
}

.trend-down {
  color: #f56c6c;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

